package com.example.demo.controller;

import com.example.demo.identity.RecommendFriends;
import com.example.demo.identity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.services.RedisService;
import com.example.demo.services.UserService;
import com.example.demo.utils.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/camelia")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    private static UserMapper userMapper;
    private static JwtUtil jwtUtil;
    private static TokenUtils tokenUtils;

    @Autowired
    private HttpClientUtils httpClientUtils;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;

    public UserController(UserMapper userMapper, JwtUtil jwtUtil, TokenUtils tokenUtils) {
        UserController.userMapper = userMapper;
        UserController.jwtUtil = jwtUtil;
        UserController.tokenUtils = tokenUtils;
    }

    @PostMapping("/login")      // 登录
    public ResponseEntity<Map<String, Object>> login(@RequestBody User user) {
        ResponseMessage message = new ResponseMessage();
        try {
            User userResult = userMapper.checkUser(user);
            if (userResult != null) {
//                验证密码是否正确
                boolean isPasswordCorrect = BCrypt.checkpw(user.getPassword(), userResult.getPassword());
                if (isPasswordCorrect) {
//                    更新当前用户信息
                    JwtUtil.setCurrentUserId(user.getUu_id());
                    //             生成JWT token
                    String token = generateUserToken(userResult);
                    userMapper.updateToken(token, user.getUsername());
//                更新token（每次登录都会生成一个新的token）
                    userMapper.updateToken(token, user.getUsername());
//                返回jwt     查询用户信息并返回
                    User realUser = userMapper.getUserInfo(user);
                    return message.responseMessage("登录成功", HttpStatus.OK, realUser, token);
                } else {
                    return message.responseMessage("用户身份验证失败", HttpStatus.UNAUTHORIZED);
                }
            } else {
                return message.responseMessage("登录失败", HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return message.responseMessage(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/registry")
    public ResponseEntity<Map<String, Object>> registry(@RequestBody User user) {
        ResponseMessage message = new ResponseMessage();
        try {
            // 检查用户名是否已存在
            User status = userMapper.checkUser(user);
            if (status != null) {
                return message.responseMessage("用户已存在", HttpStatus.CONFLICT);
            }

            // 加密密码
            String encryptedPassword = encryptPassword(user.getPassword());
            user.setPassword(encryptedPassword);

            // 生成 UUID
            String uuId = createUUID(user.getUsername());
            user.setUu_id(uuId);

            //                注册的时候随机生成一个用户头像
            String url = "https://v2.xxapi.cn/api/head";
//            String avatar = HttpClientUtils.sendGetRequest(url);
            user.setAvatar(HttpClientUtils.sendGetRequest(url));

            String token = generateUserToken(user);
            user.setToken(token);

            // 插入用户
            int result = userMapper.insertUser(user);
            if (result == 1) {

                // 获取用户信息并过滤敏感字段
                User realUser = userMapper.getUserInfo(user);
//                realUser.setPassword(null); // 过滤密码字段

                JwtUtil.setCurrentUserId(user.getUu_id());

                return message.responseMessage("注册成功", HttpStatus.OK, realUser, token);
            } else {
                return message.responseMessage("注册失败", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return message.responseMessage("服务器内部错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/validToken")
    public ResponseEntity<Map<String, Object>> validToken(@RequestHeader("Authorization") String authorization) {
        ResponseMessage message = new ResponseMessage();
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);  // 去掉 "Bearer " 前缀
            logger.info("Received token: {}", token);

            boolean isValid = tokenUtils.isValidToken(token);
            if (isValid) {
                return message.responseMessage("token is valid", HttpStatus.OK);
            } else {
                logger.error("Invalid token: {}", token);
                return message.responseMessage("Invalid token", HttpStatus.UNAUTHORIZED);
            }
        } else {
            logger.error("Invalid Authorization header: {}", authorization);
            return message.responseMessage("Invalid Authorization header", HttpStatus.BAD_REQUEST);
        }
    }

    //    动态更新用户信息
    @PostMapping("/update")
    public String updateUserInfo(@RequestParam String userId, @RequestBody Map<String, Object> updateFields) {
        boolean isSuccess = userService.updateUserInfo(userId, updateFields);
        return isSuccess ? "更新成功" : "更新失败";
    }

    //    获取天气信息
    @GetMapping("/get-ip-info")
    public ResponseEntity<Map<String, Object>> getWeatherInfo() {
        HashMap<String, Object> result = httpClientUtils.getIp();
        return ResponseEntity.ok(result);
    }


    //    随机获取用户信息
    @GetMapping("/random-recomment-friends")
    public ResponseEntity<Map<String, Object>> randomRecommendFriends() {
        List<RecommendFriends> result = userMapper.recommendFriends();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", result);
        return ResponseEntity.ok(resultMap);
    }


    //    获取好友请求消息列表
    @PostMapping("/get-friend-request-message-info/{chatId}")
    public ResponseEntity<Map<String, Object>> getFriendRequestMessageInfoList(@PathVariable("chatId") String chatId) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Map<Object, Object>> friendRequestMessageInfoList = redisService.getAllFriendRequests(chatId, 0, 10);
            if (!friendRequestMessageInfoList.isEmpty()) {
                resultMap.put("data", friendRequestMessageInfoList);
                return ResponseEntity.ok(resultMap);
            } else {
                resultMap.put("data", "暂无好友请求信息");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resultMap);
            }
        } catch (Exception e) {
            logger.info("获取好友请求消息出现错误：{}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    //    获取用户好友信息列表
    @PostMapping("/get-user-friend-info-list")
    public ResponseEntity<Map<String, Object>> getUserFriendInfoList(@RequestParam String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Map<String, Object>> friendList = redisService.getUserFriendList(userId);
            if (!friendList.isEmpty()) {
                resultMap.put("data", friendList);
                return ResponseEntity.ok(resultMap);
            }
            resultMap.put("data", "暂无好友");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resultMap);
        } catch (Exception e) {
            logger.error(e.getMessage());
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            return null;
        }
    }

    //    同意好友请求    这个接口作废，转换为WebSocket通信处理
//    @PostMapping("/accept-friend-request/{fromUserId}/{toUserId}")
    @PostMapping("/accept-friend-request/{toUserId}")
    public void acceptFriendRequest(@PathVariable("toUserId") String toUserId, @RequestBody Map<String, Object> friendRequest) throws JsonProcessingException {
        if (!friendRequest.containsKey("fromUserId")) {
            throw new IllegalArgumentException("Invalid friend request: fromUserId is missing");
        }
        String fromUserId = friendRequest.get("fromUserId").toString();
        if (fromUserId == null || fromUserId.trim().isEmpty()) {
            throw new IllegalArgumentException("Invalid fromUserId: cannot be null or empty");
        }
        User fromUserFriend = userMapper.getFriendUserByUuId(fromUserId);
        User toUserFriend = userMapper.getFriendUserByUuId(toUserId);
//        对查询的用户信息做一个处理
        if (fromUserFriend == null || toUserFriend == null) {
            throw new IllegalArgumentException("Cannot find from user or to user");
        }
//        构建from用户信息和to用户信息映射
        Map<String, String> fromMap = Map.of("friendId", fromUserFriend.getUu_id(), "friendName", fromUserFriend.getUsername(), "friendAvatar", fromUserFriend.getAvatar());
        Map<String, String> toMap = Map.of("friendId", toUserId, "friendName", toUserFriend.getUsername(), "friendAvatar", toUserFriend.getAvatar());
//        在redis中处理同意好友请求的信息
        redisService.acceptFriendRequest(fromMap, toMap);
    }

    //    删除/拒绝好友请求信息
    @DeleteMapping("/refuse-friend-request-info")
    public ResponseEntity<Map<String, Object>> refuseFriendRequest(@RequestParam String fromUserId, @RequestParam String toUserId) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            redisService.refuseUserFriendRequest(fromUserId, toUserId);
            resultMap.put("message", "refuse-1");
            return ResponseEntity.ok(resultMap);
        } catch (Exception e) {
            logger.error(e.getMessage());
            resultMap.put("message", "refuse-0");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
        }
    }


    @PostMapping("/update-type-of-friendship/{uu_id}")
    public ResponseEntity<Map<String, Object>> updateTypeOfFriendship(@PathVariable("uu_id") String uuId, @RequestBody List<String> typeOfFriendship) {
        ResponseMessage responseMessage = new ResponseMessage();
//        这里可以先添加一个select获取存在的标签信息，后期再优化
        try {
//            将列表转换为JSON数组格式的字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonTypeOfFriendship = objectMapper.writeValueAsString(typeOfFriendship);
//            更新数据库
            userMapper.updateTypeOfFriendShips(uuId, jsonTypeOfFriendship);
            return responseMessage.responseMessage("标签更新成功！", HttpStatus.OK);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return responseMessage.responseMessage(e.getMessage(), HttpStatus.INSUFFICIENT_STORAGE);
        }
    }


    //    修改用户个人信息
    @PostMapping("/update-user-info/{uu_id}")
    public void updateUserInfo(@PathVariable("uu_id") String uuId, @RequestBody User user) {
        System.out.println(user);
        try {
            if (user == null) {
                throw new IllegalArgumentException("User object cannot be null");
            }
            user.setUu_id(uuId);
            userMapper.updateUserBasicInfo(uuId, user);
        } catch (IllegalArgumentException e) {
            // 捕获 IllegalArgumentException，通常是由于输入参数无效引起的
            logger.error("Invalid input: {}", e.getMessage(), e);
        } catch (org.apache.ibatis.exceptions.PersistenceException e) {
            // 捕获 MyBatis 的 PersistenceException，通常是由于数据库操作失败引起的
            logger.error("Database operation failed: {}", e.getMessage(), e);
        } catch (Exception e) {
            // 捕获其他所有异常
            logger.error("Unexpected error occurred: {}", e.getMessage(), e);
        }
    }

    //    加密密码
    private String encryptPassword(String password) {
        // 生成盐值，workload 参数表示加密强度（推荐值为 12）
        String salt = BCrypt.gensalt(12);
        // 使用盐值加密密码
        String encryptedPassword = BCrypt.hashpw(password, salt);
        return encryptedPassword;
    }

    //    用户生成uuId
    public String createUUID(String username) {
        String uuId = UUID.randomUUID().toString().substring(0, 15);
        userMapper.updateUserUuId(uuId, username);
        return uuId;
    }


    private String generateUserToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        claims.put("uuId", user.getUu_id());
//        设置token有效期一小时
//        long validityPeriodMillis = 60 * 60 * 1000;
//        设置token有效期为一周
        long validityPeriodMillis = 7 * 24 * 60 * 60 * 1000;
        return jwtUtil.generateToken(claims, user.getUsername(), validityPeriodMillis);
    }


}
